<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html>
<head>
  <title>Calendar</title>  
	
  <!-- these are needed for the calendar. -->
  <%= javascript_include_tag "_loader.js" %>
  
  <%= csrf_meta_tag %>  
  
    <%= javascript_tag "var AUTH_TOKEN = #{form_authenticity_token.inspect};" if protect_against_forgery? %>
  
<script type='text/javascript'>

	$(document).ready(function() {
	
	/* initialize the external events
		-----------------------------------------------------------------*/
	
		$('#external-events div.external-event').each(function() {
		
			// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
			// it doesn't need to have a start or end
			var eventObject = {
				title: $.trim($(this).text()) // use the element's text as the event title
			};
			
			// store the Event Object in the DOM element so we can get to it later
			$(this).data('eventObject', eventObject);
			
			// make the event draggable using jQuery UI
			$(this).draggable({
				zIndex: 999,
				revert: true,      // will cause the event to go back to its
				revertDuration: 0  //  original position after the drag
			});
			
		});
	
		var date = new Date();
		var d = date.getDate();
		var m = date.getMonth();
		var y = date.getFullYear();

		var calendar = $('#calendar').fullCalendar({
			header: {
				left: 'prev,next today',
				center: 'title',
				right: 'resourceDay,resourceWeek,resourceMonth'
			},
			defaultView: 'resourceDay',
			firstDay: 1,
            <% if current_user.permission.wo_maintenance %>
			editable: true,
            <% else %>
            editable: false,
            <% end %>
            selectable: false,
			minTime: 0,
			maxTime: 24,	
			selectHelper: true,
			droppable: true, // this allows things to be dropped onto the calendar !!!
			resources: '/events/getresource',
			//rails engine will generate this block manually
			
			eventSources: [
            <% if current_user.permission.resources %>
			<% current_user.permission.resources.each_with_index do |t,index| %>
			{
			url: '/events/?resourceid=<%= t.id %>',
			color: '<%= t.color %>',
			textColor: '<%= t.textcolor %>',
			ignoreTimezone: true
			} <% if index != current_user.permission.resources.length-1 %> , <% end %>
			<% end %>
            <% end %>
			],
			

			
			
			//events: [
			//	{
			//		title: 'Lunch 12.15-14.45',
			//		description: 'test event',
			//		start: new Date(y, m, d, 12, 15),
			//		end: new Date(y, m, d, 14, 45),
			//		allDay: false,
			//		resource: ['1','2']
			//	}
			//],
			select: function(start, end, allDay, jsEvent, view, resource) {
				var title = prompt('event title:');
				
				if (title) {
					calendar.fullCalendar('renderEvent',
						{
							title: title,
							start: start,
							end: end,
							allDay: allDay,
							resource: resource.id
						},
						true // make the event "stick"
					);
				}
				calendar.fullCalendar('unselect');
			},
			
drop: function( date, allDay, test3, test4, resource ) { 
		//var enddate = new Date();
		var curd = date.getDate();
		var curm = date.getMonth();
		//Because month in js starts from "00"
		var curm_rails = curm+1;
		var cury = date.getFullYear();
		var curh = date.getHours();
		var curmin = date.getMinutes() + parseInt((parseFloat($(this).attr("standard_time")) % 1)*60);
		var duration = parseInt($(this).attr("standard_time"));
		var endhour = curh + duration;
		var endtime = new Date(cury, curm, curd, endhour, curmin)
		var start_time = generateRailsStartTime(date);
		var end_time = generateRailsEndTime(date,$(this).attr("standard_time"));
		//refreshCalendar(calendar)
		//alert($(this).attr("id"));
		//alert($(this).attr("duration"));	
		updateDragEvent($(this).attr("id"),start_time,end_time,false,resource,$(this).text(),'description');
		//Calendar will render "red" if the assigned time is too late
		//alert(date.getTime() + "---" + $(this).attr("due"));
			calendar.fullCalendar('renderEvent',
						{	
							id: $(this).attr("id"),
							title: $(this).text(),
							start: date,
							end: endtime,
							allDay: false,
							resource: resource.id,
							color: '#ff0000'
						},
						false // make the event "stick"
					);	

					// if so, remove the element from the "Draggable Events" list
					$(this).remove();

					calendar.fullCalendar( 'refetchEvents' )

				
			},
			eventMouseover: function(calEvent, jsEvent) {
				$.ajax({
					url: "/events/getworkorderinfo",	
					type: "GET",
				data: {
					id : calEvent.id,
					timezone : "<%= current_user.project.time_zone %>"
				},
				success: function(resp){ 
		
				// alert(eventobject.attr('id') + "zzz");
				//alert(resp);
				obj = jQuery.parseJSON(resp);
				//alert(obj);
				//var position = eventobject.position();
				$('div.tooltip').remove();
				var tooltipstr='<div class="tooltip">'+
				'<b>Work order date: </b>' +obj.work_order_date +
				'<br><b>Work order NO.: </b>' +obj.title +
				'<br><b>Work order type: </b>' +obj.workordertype +
				'<br><b>Work order description: </b>' +obj.description +
				'<br><b>Due date: </b>' +obj.due_date +
				'<br><b>Priority: </b>' +obj.priority +
				'<br><b>Customer name: </b>' +obj.customer_name +
				'<br><b>Sales order NO. :</b>' +obj.sales_order_number +
				' </div>';			
				$(tooltipstr).appendTo('body');
				var tooltipX = jsEvent.pageX;
				var tooltipY = jsEvent.pageY;
				$('div.tooltip').css({top: tooltipY, left: tooltipX});					
				//changeTooltipPosition(event);
		
			},
			error: function(resp){ 
			//alert(resp);
			//alert("cannot retrieve data!");
			}
  
		}).mousemove(function(e) {
			alert("cannot retrieve data!");
			var tooltipX = event.pageX - 8;
			var tooltipY = event.pageY + 8;
			$('div.tooltip').css({top: tooltipY, left: tooltipX});
				}	
				);
			},

			eventMouseout: function(calEvent, jsEvent) {
				$(this).css('z-index', 8);
				$('div.tooltip').remove();
			},
			eventDrop: function( event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view ) { 
				updateEvent(event);

				alert('event moved to' + generateRailsEndTime(event.end) + ':: ' + event.resource);
				
			},
			eventResize: function( event, dayDelta, minuteDelta, revertFunc, jsEvent, ui, view ) { 
				updateEvent(event);
				alert('event was resized, new endtime: '+event.end);
			},
			eventClick: function ( event, jsEvent, view )  {
				alert('event '+event.title+' was left clicked');
			},			
			eventRender: function( event, element, view ) { 
				element.bind('contextmenu',function(e){
					$('div.tooltip').remove();
					$('#contextMenuContainer').html('<div class=\'contextMenu\'>Actions:<br><br><input type=\'button\' value=\'Job Details\' onClick="popJobDetails(\''+event.id+'\')"><br><input type=\'button\' value=\'Unassign\' onClick="removeJob(\''+event.id+'\')"></div>');	
					$('#contextMenuContainer').fadeIn();
					var position = element.position();
					$('#contextMenuContainer').css({
						left : position.left+20,
						top  : position.top+80
					});
					$(document).click(function()   {
						$('#contextMenuContainer').fadeOut();
					});
					return false;
				});
			},
			height: calcCalendarHeight()
		});
		
		function calcCalendarHeight() {
			var h = $(window).height() - 40;
			return h;
		}
		
		$(window).resize(function() {
			$('#calendar').fullCalendar('option', 'height', calcCalendarHeight());
		});
	});

function popJobDetails(id) {
	alert(id);
}

function removeJob(event_id) {
	var removeConfirm = confirm("Do you really want to unassign this job?");
	if (removeConfirm== true)
	{
		$('#calendar').fullCalendar('removeEvents', event_id);
		removeEvent(event_id);
	}
}
	
function refreshCalendar(calendar) {
    calendar.fullCalendar( 'refetchEvents' );
}

function updateEvent(event) {

$.ajax({
    url: "/events/update",
    type: "POST",
    data: {
		id : event.id,
                timezone : "<%= current_user.project.time_zone %>",
		event: {
                         starts_at: generateRailsStartTime(event.start),
			 ends_at: generateRailsEndTime(event.end,0),
			 resource_id : event.resource
	}},
    success: function(resp){ }
});
};

function removeEvent(event_id) {

$.ajax({
    url: "/events/unassignevent",
    type: "POST",
    data: {
		id : event_id,
	},
    success: function(resp){ }
});
};

function updateDragEvent(id,start,enddate,allday,resource_id,title,description) {
$.ajax({
    url: "/events/update",
    type: "POST",
    data: {
			id: id,
            timezone : "<%= current_user.project.time_zone %>",
            event: { 
			 starts_at: start,
			 ends_at: enddate,
			 all_day: allday,
			 resource_id : resource_id.id,
			 //title: title,
			 description: description
	}},
    success: function(resp){ }
});
};

function generateRailsStartTime(date) {
		//var enddate = new Date();
		var curd = date.getDate();
		var curm = date.getMonth();
		//Because month in js starts from "00"
		var curm_rails = curm+1; 
		var cury = date.getFullYear();
		var curh = date.getHours();
		var curmin = date.getMinutes();
		var duration = 1;
		var endhour = curh+duration;
		var endtime = new Date(cury, curm, curd, endhour, curmin)
		
		var start_time = cury + "-" + curm_rails + "-" + curd + " " + curh + ":" + curmin;
		//var end_time = cury + "-" + curm_rails + "-" + curd + " " + endhour + ":" + curmin;
		
		return start_time;
};

function generateRailsEndTime(date,duration) {
		//var enddate = new Date();
		var curd = date.getDate();
		var curm = date.getMonth();
		//Because month in js starts from "00"
		var curm_rails = curm+1; 
		var cury = date.getFullYear();
		var curh = date.getHours();
		var curmin = date.getMinutes() + parseInt((parseFloat(duration % 1)*60));
		if (curmin >= 60) {
            var endhour = curh + parseInt(duration) + 1;
            curmin -= 60
        } else {
            var endhour = curh + parseInt(duration)
        }
        
        //var duration = 1;
        
        //alert(duration + "::" + curmin + "::" +  endhour)
		
		var endtime = new Date(cury, curm, curd, endhour, curmin)
		
		//var start_time = cury + "-" + curm_rails + "-" + curd + " " + curh + ":" + curmin;
		var end_time = cury + "-" + curm_rails + "-" + curd + " " + endhour + ":" + curmin;
		
		return end_time;
};

function showWorkorderDetails(id) {
	//alert(id);

};

function renderWorkorderPopup(eventobject) {
 //var woinfo = getWorkorderInfo(eventobject.attr('id'));
 $.ajax({
    url: "/events/getworkorderinfo",
    type: "GET",
    data: {
  id : eventobject.attr('id'),
  },
    success: function(resp){ 
  //alert(resp);
 // alert(eventobject.attr('id') + "zzz");
  var obj = jQuery.parseJSON(resp);
  var position = eventobject.position();
  },
   error: function(resp){ 
  //alert(resp);
  //alert("cannot retrieve data!");
 }
  
});

}

//tooltip

$(document).ready(function() {
	//var obj = null;
	var changeTooltipPosition = function(event) {
	  var tooltipX = event.pageX - 8;
	  var tooltipY = event.pageY + 8;
	  $('div.tooltip').css({top: tooltipY, left: tooltipX});
	};
 
	var showTooltip = function(event) {
	  //alert(event.currentTarget.id);
	  
	$.ajax({
		url: "/events/getworkorderinfo",
		type: "GET",
		data: {
			id : event.currentTarget.id,
			timezone : "<%= current_user.project.time_zone %>" 
		},
		success: function(resp){ 
		
		// alert(eventobject.attr('id') + "zzz");
		//alert(resp);
		obj = jQuery.parseJSON(resp);
		//alert(obj);
		//var position = eventobject.position();
		$('div.tooltip').remove();
		var tooltipstr='<div class="tooltip">'+
		'<b>Work order date: </b>' +obj.work_order_date +
		'<br><b>Work order NO.: </b>' +obj.title +
		'<br><b>Work order type: </b>' +obj.workordertype +
		'<br><b>Work order description: </b>' +obj.description +
		'<br><b>Due date: </b>' +obj.due_date +
		'<br><b>Priority: </b>' +obj.priority +
		'<br><b>Customer name: </b>' +obj.customer_name +
		'<br><b>Sales order NO. :</b>' +obj.sales_order_number +
		' </div>';
		$(tooltipstr).appendTo('body');
		var tooltipX = event.pageX - 8;
		var tooltipY = event.pageY + 8;
		$('div.tooltip').css({top: tooltipY, left: tooltipX});	
		
	},
	error: function(resp){ 
		//alert(resp);
		//alert("cannot retrieve data!");
	}
  
	});	  
	  
	 // if (obj != null) {
		//alert(obj.id);
		//obj = null;
	  
	  //$('div.tooltip').remove();
	 
	  //}
	
	};
 
	var hideTooltip = function() {
	   $('div.tooltip').remove();
	};
 
	$("[wid*=wo]").bind({
	   //mousemove : changeTooltipPosition,
	   mouseenter : showTooltip,
	   mouseleave: hideTooltip,
	   drag:hideTooltip
	});
});



</script>
<style type='text/css'>
	#hint{
		cursor:pointer;
	}

	.tooltip{
	margin:8px;
	padding:8px;
	border:1px solid blue;
	background-color:yellow;
	position: absolute;
	z-index: 1000;
	text-align:left;
	font-size:12px;
	}
	
	.priority_button {
	-moz-box-shadow:inset 0px 1px 0px 0px #bbdaf7;
	-webkit-box-shadow:inset 0px 1px 0px 0px #bbdaf7;
	box-shadow:inset 0px 1px 0px 0px #bbdaf7;
	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #79bbff), color-stop(1, #378de5) );
	background:-moz-linear-gradient( center top, #79bbff 5%, #378de5 100% );
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#79bbff', endColorstr='#378de5');
	background-color:#79bbff;
	-moz-border-radius:6px;
	-webkit-border-radius:6px;
	border-radius:6px;
	border:1px solid #84bbf3;
	display:inline-block;
	color:#ffffff;
	font-family:arial;
	font-size:12px;
	font-weight:bold;
	padding:6px 24px;
	text-decoration:none;
	text-shadow:1px 1px 0px #528ecc;
	}
	
	.priority_button:hover {
	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #378de5), color-stop(1, #79bbff) );
	background:-moz-linear-gradient( center top, #378de5 5%, #79bbff 100% );
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#378de5', endColorstr='#79bbff');
	background-color:#378de5;
	}
	
	.priority_button:active {
	position:relative;
	top:1px;
	}
	
	.duedate_button {
	-moz-box-shadow:inset 0px 1px 0px 0px #ffffff;
	-webkit-box-shadow:inset 0px 1px 0px 0px #ffffff;
	box-shadow:inset 0px 1px 0px 0px #ffffff;
	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ededed), color-stop(1, #dfdfdf) );
	background:-moz-linear-gradient( center top, #ededed 5%, #dfdfdf 100% );
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ededed', endColorstr='#dfdfdf');
	background-color:#ededed;
	-moz-border-radius:6px;
	-webkit-border-radius:6px;
	border-radius:6px;
	border:1px solid #dcdcdc;
	display:inline-block;
	color:#777777;
	font-family:arial;
	font-size:12px;
	font-weight:bold;
	padding:6px 24px;
	text-decoration:none;
	text-shadow:1px 1px 0px #ffffff;
	}
	
	.duedate_button:hover {
	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #dfdfdf), color-stop(1, #ededed) );
	background:-moz-linear-gradient( center top, #dfdfdf 5%, #ededed 100% );
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#dfdfdf', endColorstr='#ededed');
	background-color:#dfdfdf;
	}
	
	.duedate_button:active {
	position:relative;
	top:1px;
	}
	
	.contextMenuContainer {
	        background-color:#f0f0f0;
		width: 100px;
		height: 100px;
		display: none;
		border-radius: 5px;
		border: 1px solid black;
		position: relative;
	}
	
	.contextMenu {
		position:absolute;
		left:5px;
		top:0px;			
	}
	
	body {
		margin-top: 40px;
		text-align: center;
		font-size: 14px;
		font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
		}
		
	#wrap {
		width: 1126px;
		margin: 0 auto;
		}
		
	#external-events {
		float: left;

		padding: 0 28px;
		border: 3px solid #DDDDDD;
		#background: #eee;
		text-align: left;
		height: 150 px;
		width: 1200 px;
		font-size: 12.5px;
		}
		
	#external-events h4 {
		font-size: 16px;
		margin-top: 0;
		padding-top: 1em;
		}
		
	.external-event { /* try to mimick the look of a real event */
		margin: 2px 0;
		padding: 2px 4px;
		background: #3366CC;
		color: #fff;
		font-size: .85em;
		cursor: pointer;
		}
		
	#external-events p {
		margin: 1.5em 0;
		font-size: 11px;
		color: #888;
		}
		
	#external-events p input {
		margin: 0;
		vertical-align: middle;
		
		}

	#calendar {
		margin: 0px 0;
		padding: 2px 4px;
		float: right;
		width: 1260px;
		height: 500px;
		border: 3px solid #DDDDDD;
		overflow: relative
		
		}
	.tableborder {
		border: 3px solid #DDDDDD;
		cellpadding: 0px;
		cellspacing: 0px;
		width: 100%
	}
	
	.externalheader {
		color: #FFA500;
	}
	

</style>
</head>
<body>
<% if user_signed_in? %>
<%= current_user.email %>
<p align="right"><%= link_to "Add wordorder", :controller => "events", :action => "new" %> | <%= link_to "Add workorder type", :controller => "events", :action => "newworkordertype" %> | <%= link_to "Add resource group", :controller => "events", :action => "newresourcegroup" %> | <%= link_to "Add resource", :controller => "events", :action => "newresource" %></p>

<br>
<p>
<table border = 0>
	<tr>
		<td>
			<table border = 0 width = 100%>
				<tr>
					<td width = 18%>
						<table border = 0>
							<tr>
								<td>
									<table height=50 class="tableborder">
										<tr>
											<td>
												<select width = 100%>
												<option>NOV 1, 2012 - Dec 15, 2012</option>
												<option>NOV 16, 2012 - Dec 30, 2012</option>
												</select>
											</td>
										</tr>
									</table>
								</td>
							</tr>
							<tr>
								<td>
									<table height=50 class="tableborder">
										<tr>
											<td>
											<%= button_to "Priority", '/hello/index?order_by=priority' , :class => 'priority_button'%>
											<%= button_to "Due date", '/hello/index?order_by=due_date' , :class => 'duedate_button'%>
											<!-- <button class="priority_button">Priority</button><button class="duedate_button">Due Date</button> -->
											</td>

										</tr>
									</table>
								</td>
							</tr>
						
						</table>
					</td>
					<td>
						
					</td>
				</tr>
			</table>
		</td>
	</tr>
	<tr>
		<td>

<table height = 100 style="margin-left:2px;">
<tr>
<td>


<div id='wrap'>

<div id='external-events'>
<table>

<% @temp_workordertype_id = 0 %>
<% @unassigned_events.each do |t| %>
	<% if @temp_workordertype_id != t.workordertype_id %>
	<tr>
	<%end%>
	<td>
	<div class='external-event'  <% if datetimecompare(Time.now.to_i,t.due_date.to_i) == false %> style='background-color:<%= t.workordertype.color%>;width: 80px;color: #000000;' <% end %>  id="<%= t.id %>" wid="wo<%= t.id %>" due=<%= t.due_date.to_i %> standard_time=<%= t.workordertype.standard_time.to_f %>> <%= t.priority %> (<%= t.due_date.day %>) <%= t.title %> <%= @temp_workordertype_id%> <%= t.workordertype_id %></div>
	</td>	
	<% @temp_workordertype_id = t.workordertype_id%>
	<% if @temp_workordertype_id != t.workordertype_id %>
	</tr>
	<%end%>	
<%end%>
</table>

</table>
		</td>
	</tr>
</table>
</table>
</div>
<div id='calendar'></div>
<div id='contextMenuContainer' class="contextMenuContainer"></div>


<% else %>
Please sign-in first
<% end %>
</body>
</html>